public class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        int len1 = text1.length();
        int len2 = text2.length();

        char[] ch1 = text1.toCharArray();
        char[] ch2 = text2.toCharArray();

        //text1的0-i的子串，text2的0-j的子串中最长公共子序列的长度
        int[][] dp = new int[len1 + 1][len2 + 1];

        for (int i = 1; i < len1 + 1; i++) {//从上到下
            for (int j = 1; j < len2 + 1; j++) {//从左往右
                if (ch1[i - 1] == ch2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(Math.max(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]);
                }
            }
        }

        return dp[len1][len2];
    }
}
